<template>
  <div class="app-container">
    <div id="title" style="font-size: 30px;margin-top: -20px;text-align: center;color: #00afff">已开放检测点</div>
    <div id="container">

      <div class="input-card" style="margin-top:30px">
        <label style="color:grey;font-size: 20px">增加检测点</label>
        <div class="input-item">
          <input id="addMarker" type="button" class="btn" @click="addMarker" value="增加检测点">
          <input id="setFitView" type="button" class="btn" value="地图自适应" />
<!--          <input type="button" class="btn" value="开启信息窗体" @click="openInfo"/>-->
<!--          <input type="button" class="btn" value="关闭信息窗体" @click="infoWindow.close()"/>-->
        </div>
        <div class="input-item">
          <div class="input-item-prepend"><span class="input-item-text">经纬度</span></div>
          <!--118.199143,24.496298-->
          <input id='lnglat' type="text" value=''>
        </div>
        <div class="input-item">
          <div class="input-item-prepend"><span class="input-item-text" >地址</span></div>
          <input id='caddress' type="text" disabled>
        </div>

      </div>

      <!--抽屉-->
      <div>
        <el-drawer
          title="增加检测点"
          :visible.sync="drawer"
          :direction="direction"
          ref="navDrawer"
          :before-close="handleClose">

          <el-form :label-position=" labelPosition" label-width="80px" ref="ruleForm" :model="ruleForm"
                   hide-required-asterisk>
            <el-form-item label="详细位置:">
              <el-input v-model="ruleForm.caddress" disabled></el-input>
            </el-form-item>
            <el-form-item
              prop="cpname"
              :rules="[
            { required: true, message: '请输入检测点名字！', trigger: 'blur' },
            ]"
              label="检测点名:">
              <el-input id="cpname" v-model="ruleForm.cpname"></el-input>
            </el-form-item>
            <el-form-item label="经度:">
              <el-input v-model="ruleForm.longitude" disabled></el-input>
            </el-form-item>
            <el-form-item label="纬度:">
              <el-input v-model="ruleForm.latitude" disabled></el-input>
            </el-form-item>

            <div class="demo-drawer__footer" style="text-align: center">
              <!--              <el-button @click="cancelForm">取 消</el-button>-->
              <el-button type="warning" @click="resetForm('ruleForm')" icon="el-icon-delete">重置</el-button>
              <el-button type="primary" @click="sureCommit" icon="el-icon-search">提交</el-button>
            </div>
          </el-form>
        </el-drawer>
      </div>

      <div id="myPageTop">
        <table>
          <tr>
            <td>
              <label style="color: #00afff">请输入要搜索的地址：</label>
            </td>
          </tr>
          <tr>
            <td>
              <input id="tipinput" placeholder="地址"/>
            </td>
          </tr>
        </table>
      </div>

    </div>




  </div>
</template>
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=8f006ad751934ff23a4899e153227982&plugin=AMap.Geocoder"></script>
<script type="text/javascript" src="https://cache.amap.com/lbs/static/addToolbar.js"></script>
<script>
  var map;
  var infoWindow;
  import { listCheckpoint, getCheckpoint, addCheckpoint } from "@/api/whc/checkpoint";
  export default {
    data() {
      return {
        address: [],
        lngMain:0,
        latMain:0,
        drawer: false,
        direction: 'rtl',
        //抽屉表单
        labelPosition: 'right',
        ruleForm: {
          caddress: '',
          cpname: '',
          longitude: '',
          latitude:''
        }
      };
    },
    created() {
      //生成自定义的图标
      let icon = new AMap.Icon({
        image: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
        size: new AMap.Size(25, 35),
        imageSize: new AMap.Size(25, 35)
      });
      this.loading = true;
      //获取检测点
      listCheckpoint({ pageSize: 100000}).then(response => {
        this.$data.address=response.rows
        this.loading = false;
        console.log(response.rows+"--------------")
      }).then(()=>{
        //循环生成标记点
        for (let i = 0; i < this.$data.address.length; i++) {
          //判断该检测点是否为启用状态 0 启用  1停用
          if (this.$data.address[i].cpstatus == 0){
            //初始化覆盖物对象并赋值给vue对象
            var marker = new AMap.Marker({
              icon: icon, //使用自定义的图标
              position: [this.$data.address[i].longitude, this.$data.address[i].latitude] //覆盖物位置坐标
            });
            marker.setLabel({
              direction:'right',
              offset: new AMap.Pixel(0, -10),  //设置文本标注偏移量
              content: "<div class='info' style='width: 50px'>"+this.$data.address[i].cpname+"</div>", //设置文本标注内容
            });

            map.add(marker); //添加覆盖物到地图
          }
        }
      }).then(()=>{
        this.open2("查找检测点成功");
      })
    },
    mounted() {
      //地图组件绑定div进行初始化并赋值给vue的对象
      map = new AMap.Map("container", {
        center: [118.0677777, 24.44611], //设置显示的地图中心坐标
        zoom: 8, //设置地图缩放等级
        viewMode:'3D',
        resizeEnable: true
      });
      //生成自定义的图标
      let icon = new AMap.Icon({
        image: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png",
        size: new AMap.Size(25, 35),
        imageSize: new AMap.Size(25, 35)
      });
      //生成标记点
      var marker = new AMap.Marker({
        resizeEnable: true,
        icon: icon,
        position: [this.lngMain,this.latMain], //118.176464,24.489582
        offset: new AMap.Pixel(-13, -30),
        // 设置是否可拖拽
        // draggable: true,

      });
      // 设置点标记的动画效果，此处为弹跳效果
      // marker.setAnimation('AMAP_ANIMATION_BOUNCE');
      //绑定地图组件内单击事件
      map.on('click', (e) => {
        this.lngMain = e.lnglat.getLng()
        this.latMain = e.lnglat.getLat()
        document.getElementById('lnglat').value = e.lnglat;
        //将经纬度转化
        this.initi(e.lnglat);

        //地图增加标记点
        map.add(marker);
        //设置标记点随鼠标点击移动
        marker.setPosition(document.getElementById('lnglat').value.split(","));
      });
      //地图组件
      AMap.plugin(['AMap.ToolBar','AMap.Scale','AMap.OverView'],function(){
        map.addControl(new AMap.ToolBar());
        map.addControl(new AMap.Scale());
      })

      // 添加事件监听, 使地图自适应显示到合适的范围
      AMap.event.addDomListener(document.getElementById('setFitView'), 'click', function() {
        var newCenter = map.setFitView();
      });


      //搜索功能
      var placeSearch
      var auto
      AMap.service('AMap.PlaceSearch',function(){
        //输入提示
        var autoOptions = {
          input: "tipinput"
        };
        auto = new AMap.Autocomplete(autoOptions);
        placeSearch = new AMap.PlaceSearch({
          map: map
        });  //构造地点查询类
      });
      function select(e) {
        placeSearch.search(e.poi.name);  //关键字查询查询
        placeSearch.setCity(e.poi.adcode);
      }
      AMap.event.addListener(auto, "select", select);//注册监听，当选中某条记录时会触发
      //关键字搜索
    },
    methods: {
      //增加标记点
      addMarker(){
        //鼠标点击获取到的坐标--------------------------------------------------------------
        console.log(this.lngMain+","+this.latMain)
        //判断该点是否合法
        if (this.lngMain === 0){
          this.open3("请点击地图中的地址作为检测点")
        }else {
          //抽屉展示
          this.$data.drawer = true
          //将经纬度和详细位置发送复制到抽屉中
          this.ruleForm.longitude=this.lngMain
          this.ruleForm.latitude=this.latMain
          this.ruleForm.caddress=document.getElementById("caddress").value;
        }

      },

      //经纬度获取地址
      initi (lnglatXY) {
        // console.log("lnglatXY的值为======"+lnglatXY)
        var lng = document.getElementById('lnglat').value;
        // console.log(lng);
        AMap.plugin('AMap.Geocoder', function () {
          var geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: "all"
          });
          var latxy = lng.split(",");
          // console.log(latxy,148)
          latxy = latxy.map(item=>{
            return parseFloat(item);
          })
          // console.log(latxy,152)
          geocoder.getAddress(latxy, function (status, result) {
            if (status === 'complete' && result.info === 'OK') {
              var address = result.regeocode.formattedAddress;
              document.getElementById('caddress').value = address;
            } else {
              this.open3("查询错误，请重新选择地点");
            }
          });
        })
      },
      //提交表单中的信息发送请求
      sureCommit(){
        console.log("发送请求=====")
        this.ruleForm.cpname=document.getElementById("cpname").value;
        //获取详细地址
        var str = document.getElementById("caddress").value
        //判断是否为空格
        if (this.ruleForm.cpname.match(/^[ ]*$/)){
          this.open3("检测点地址不能为空或者空格，请重新输入")
          return;
        }
        if (str.indexOf("福建省") === -1){
          this.open3("暂未开放福建省外地区，请重新选择")
          return;
        } else {
          this.$confirm('是否提交?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            addCheckpoint(this.ruleForm).then(response => {
              // alert(response.msg)
              if (response.code === 200){
                if(response.msg === "0"){
                  this.open4("增加检测点成功")
                } else {
                  this.open3("暂不支持该地区，请重新选择")
                }
              }else {
                this.open3("请重新选择地区")
              }
            });
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消提交'
            });
          });
        }
      },
      //抽屉是否关闭
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
            this.resetForm('ruleForm')
          })
          .catch(_ => {});
      },
      //手动关闭
      cancelForm() {
        console.log("抽屉关闭-----")
        this.$refs.navDrawer.closeDrawer();
        this.resetForm('ruleForm')
      },
      //重置表单
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      open2(msg) {
        this.$message({
          message: msg,
          type: 'success'
        });
      },
      open4(msg) {
        this.$message({
          message: msg,
          type: 'success',
          duration: 2000,
          //刷新界面，重新加载站点
          onClose:window.location.reload(),
        });
      },
      open3(msg) {
        this.$message({
          message: msg,
          type: 'warning'
        });
      },


    }
  };
</script>
<style scoped>
  /* 引入外部样式 */
  @import '../../../assets/styles/map.scss';
  #container {
    width: 1600px;
    height: 700px;
  }
  .input-card{
    width: 18rem;
    z-index: 170;
    width: 400px;
  }

  .input-card .btn{
    margin-right: .8rem;
  }

  .input-card .btn:last-child{
    margin-right: 0;
  }

  .info{
    position: relative;
    top: 0;
    right: 0;
    width: 10px;
  }

  /deep/.el-drawer.rtl {
    background: #ffffff;
  }

  /deep/.el-drawer__header {
    color: #1890ff;
    font-size: 30px;
  }

  .el-drawer__body {
    margin: 0px 10px 10px 10px;
    background: rgba(19, 32, 42, 0.5) !important;
    padding: 0;
    width: 520px !important;
    height: 340px;
    position: relative;
  }

  /* 方式一：
  使用 /deep/*/
    .el-input /deep/ .el-input__inner {
      color: black;
    }
  /*  方式二
  >>> */
  .el-input >>> .el-input__inner {
    background-color: white;
  }


  .amap-info-content {
    font-size: 12px;
  }

  #myPageTop {
    z-index: 170;
    position: absolute;
    top: 5px;
    right: 10px;
    background: #fff none repeat scroll 0 0;
    border: 1px solid #ccc;
    margin: 10px auto;
    padding:6px;
    font-family: "Microsoft Yahei", "微软雅黑", "Pinghei";
    font-size: 14px;
  }
  #myPageTop label {
    margin: 0 20px 0 0;
    color: #666666;
    font-weight: normal;
  }
  #myPageTop input {
    width: 170px;
  }
  #myPageTop .column2{
    padding-left: 25px;
  }

</style>
